package com.tensquare.manager.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import util.JwtUtil;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by DUZEYU on 2019/1/2.
 * 网管过滤器 继承  一个 网管过滤器
 */
@Component
public class ManagerFilter extends ZuulFilter {
    @Autowired
    private JwtUtil jwtUtil;
    /**
     * 过滤器的类型  请求前pre或后post执行
     * @return
     */
    @Override
    public String filterType() {
        return "pre";
    }

    /**
     *  执行顺序  0就是优先执行   数字越小 就先执行
     * @return
     */
    @Override
    public int filterOrder() {
        return 0;
    }

    /**
     *  当前过滤器时候开启  true 表示开启
     * @return
     */
    @Override
    public boolean shouldFilter() {
        return true;
    }

    /**
     *  过滤器内的操作  return 任何Object值都表示执行
     * @return
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
        if (request.getMethod().equals("OPTIONS")){
            return null;
        }
        if (request.getRequestURI().indexOf("login") > 0){
            return null;
        }

        String header = request.getHeader("Authorization");
        if (null != header && !"".equals(header)){
            if (header.startsWith("Bearer ")){
                String token = header.substring(7);
                try {
                    Claims claims = jwtUtil.parseJWT(token);
                    String roles = (String) claims.get("roles");
                    if(roles.equals("admin")){
                        requestContext.addZuulRequestHeader("Authorization",header);
                        return null;
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    requestContext.setSendZuulResponse(false);// 终止运行
                }
            }
        }
        requestContext.setSendZuulResponse(false);// 终止运行
        requestContext.setResponseStatusCode(403);// 权限不足
        requestContext.setResponseBody("权限不足");
        requestContext.getResponse().setContentType("text/html;charset=utf-8");
        return null;
    }
}
